package com.example.mqtt.service;

import jakarta.annotation.Resource;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Component;

/**
 * mqtt消息订阅
 **/
@Component
public class SubService {
    @Resource
    private MqttPahoMessageDrivenChannelAdapter messageProducer;

    public String subscribeTopic(String topic) {
        return subscribeTopic(topic, 1);
    }

    public String subscribeTopic(String topic, Integer qos) {
        if (null == qos) {
            qos = 1;
        }
        addSubscription(topic, qos);
        return "订阅主题：" + topic;
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    public void addSubscription(String topic, int qos) {
        if (messageProducer != null) {
            messageProducer.addTopic(topic, qos);
        } else {
            throw new IllegalStateException("动态“添加”订阅主题");
        }
    }

    public void removeSubscription(String topic) {
        if (messageProducer != null) {
            messageProducer.removeTopic(topic);
        } else {
            throw new IllegalStateException("动态“移除”订阅主题");
        }
    }

}
